package com.gexin.controller.xapp.product;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyApi;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.controller.system.LoginController;
import com.gexin.controller.weixin.subscribe.CompanyToPerson;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.model.activity.Activity;
import com.gexin.model.activity.FreeAcquire;
import com.gexin.model.activity.MD5Util;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentCity;
import com.gexin.model.agent.AgentProductSku;
import com.gexin.model.order.Order;
import com.gexin.model.order.OrderItem;
import com.gexin.model.order.OrderPresale;
import com.gexin.model.product.ProductSku;
import com.gexin.model.product.Products;
import com.gexin.model.template.TemplateArea;
import com.gexin.model.template.TemplateWuliu;
import com.gexin.model.template.TemplateWuliuItem;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.agent.AgentService;
import com.gexin.service.freeacquire.FreeAcquireService;
import com.gexin.service.order.OrderInvoiceService;
import com.gexin.weixin.kit.WxConfigKit;
import com.gexin.weixin.kit.XMLUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.JFinal;
import com.jfinal.core.NotAction;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.gexin.controller.system.freeacquire.FreeAcquireController.freeAcquireService;

/**
 * 肖得明
 *
 * @author 肖得明
 */
//@Before(XAppSafeInterceptor.class)//统一错误拦截
@ControllerBind(controllerKey = "/xapp/order/buy")
public class OrderBuyController extends AppController {
    static Log log = Log.getLog(LoginController.class);

    public void sign() {
        String order_id = getPara("id");
        Order new_order = Order.dao.findById(order_id);
        if (new_order == null) {
            fail("订单不存在");
            return;
        }
        Order o = new Order();
        o.setId(new_order.getId());
        o.setTotalAmount(new_order.getTotalAmount());
        o.put("product_name", "小鱼儿商品支付");
        String notify_url = AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify"; //设置回调的URL
        o.put("notify_url", notify_url);
        o.setCreatetime(new Date());
        success(o);
    }


    // 签名
//    @NotAction
    public static Map<String, String> sign_pay(String order_id,BigDecimal price) {
        double money = 0.1;
        int d = 0;
        // 金额 1分钱
        if (JFinal.me().getConstants().getDevMode()) {
              log.info("_________________线下"+d);
        } else {
//            d = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(100.00)).intValue();
            d = price.multiply(BigDecimal.valueOf(100.00)).intValue();
         }
        String notify_url = AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify"; // 设置回调的URL
//         String order_id = IdGenerateUtils.getId();
        Integer current_id = 2;// 当前要签名的用户id
//        WeixinAppConfig config = WxConfigKit.cache_getConfigById(current_id);
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", "wx001ef33c1c1512d9");// 应用ID
        params.put("mch_id", "1561327181"); // 微信商户的ID
        params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
        params.put("body", "商品支付"); // 设置商品的名称 不要超过50个字符串
        params.put("out_trade_no", order_id);// 生成订单ID
        params.put("total_fee", d + "");// 支付的金额 以分为单位
        params.put("spbill_create_ip", "127.0.0.1");
        params.put("notify_url", notify_url); // 设置回调的URL 地址.
        params.put("trade_type", "APP");
        try {
            String sign = CompanyToPerson.generalSign(params  /*"1561327181""2e9e2c3fb695ab27637de08734fb991f"*/);
            params.put("sign", sign);
            String xmlResult = PaymentApi.pushOrder(params);
            Map<String, String> map = XMLUtil.doXMLParse(xmlResult);
//          二次验签
            Map hashMap = new HashMap();
            hashMap.put("appid","wx001ef33c1c1512d9");
            hashMap.put("partnerid","1561327181");
            hashMap.put("prepayid",map.get("prepay_id"));
            hashMap.put("package","Sign=WXPay");
            hashMap.put("noncestr",System.currentTimeMillis()/1000+"");
            hashMap.put("timestamp",System.currentTimeMillis()/1000+"");
            String signSecond = CompanyToPerson.generalSign(hashMap  /*"1561327181""2e9e2c3fb695ab27637de08734fb991f"*/);
            hashMap.put("sign",signSecond);
            hashMap.put("order_id",order_id);
            return hashMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void other(){
//        Page<FreeAcquire> freeAcquirePage = freeAcquireService.findList(1, 10);
//        List<FreeAcquire> freeAcquireList = freeAcquirePage.getList();
//        Boolean pracel = false;
//        if (null != productId) {
//            for (int i = 0; i < freeAcquireList.size(); i++) {
//                FreeAcquire freeAcquire = freeAcquireList.get(i);
//                String freeAcquireProductId = freeAcquire.getProductId();
//                if (StringUtils.isNotBlank(freeAcquireProductId) && freeAcquireProductId.equals(pro.getId() + "")) {
//                    BigDecimal postFee = pro.getPostFee();
//                    pracel = true;
//                    map.put("post_free", postFee);
//                }
//            }
//        }
//        map.put("pracel", pracel);
    }


    public void index() {
        String json = getPara("products");
        JSONArray data = JSONArray.parseArray(json);
        List<Products> pro_list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (Object obj : data) {
            JSONObject item = (JSONObject) obj;
            Products pro = Products.dao.getProductBaseById(item.getInteger("id"));
            String sku_id = item.getString("skuid");
            pro.put("num", item.getInteger("num"));
            pro.put("skuid", item.getString("skuid"));
            ProductSku sku = null;

            Integer productId = item.getInteger("id");


            if (StringUtil.isNotBlank(sku_id)) {
                sku = ProductSku.dao.findById(sku_id);
                if (sku != null) {
                    pro.put("sku", sku);
                    pro_list.add(pro);
                }
            } else {
                pro.put("sku", null);
                pro_list.add(pro);
            }
        }
        //初始化用户的地址
        UserAddress userAddress = UserAddress.dao.findByUserDefault(getAuthUserId());
        if (userAddress != null) {
            map.put("address", userAddress);
        } else {
            map.put("address", null);
        }
        map.put("pro_list", pro_list);
        success(map);
    }


    public void invoke() {
        FreeAcquireService freeAcquireService = new FreeAcquireService();
//		freeAcquireService.cashbackList("2633",true);
        freeAcquireService.queryFreeacquireList();
    }

    public void budget() {
        Integer product_id = getParaToInt("id");
        Map result = Products.dao.getProductsDetailByID(product_id);
        success(result);
    }

    public void exchange() {
        fail("此接口无效");
    }


    //	@Before(Tx.class)
    public void add() {

        String json = getPara("products");
        Integer addr_id = getParaToInt("addr_id", null);
        String invoices = getPara("invoices");
        if (addr_id == null) {
            fail("请选择收货地址");
            return;
        }
        UserAddress address = UserAddress.dao.findById(addr_id);
        if (address == null || address.getId() == null) {
            fail("收货地址不存在！");
            return;
        }
        //尾款通知手机号码
        String tail_notice_phone = getPara("tail_notice_phone");
        //优惠卷ID
        String coupon_id = getPara("coupon_id");
        Integer registerOrder = getParaToInt("register_order");

//		是否包邮
        Boolean pracel = getParaToBoolean("pracel");
        Integer agentId = getParaToInt("agent_id");
        //支付方式  3支付宝 4微信APP支付  5微信小程序支付 6用户余额支付
        Integer pay_type = getParaToInt("pay_type", 5);

        Integer isUserHongbao = getParaToInt("is_user_hongbao");

        Order new_order = new Order();
        new_order.setId(IdGenerateUtils.getOrderId());// 订单ID
        new_order.setPayId(new_order.getId());
        new_order.setUserId(getAuthUserId());//
        new_order.setOrderPlatform(isXapp() == true ? 1 : 2);
        new_order.setRegisterOrder(registerOrder);
        //初始化地址信息
        new_order.setExpressAddress(address.getAddress());// 收货详细信息
        new_order.setExpressReceiveName(address.getConsignee());// 收货人姓名
        new_order.setExpressZipCode("000000");// 邮编信息
        new_order.setExpressPhone(address.getPhone());// 手机号码
        new_order.setAddressId(address.getId());

        new_order.setTailNoticePhone(tail_notice_phone);

        JSONArray data = JSONArray.parseArray(json);
        BigDecimal total_money = BigDecimal.valueOf(0.0);
        BigDecimal preordain_front_money = BigDecimal.valueOf(0.0);//定金
        BigDecimal preordain_tail_money = BigDecimal.valueOf(0.0);//尾款
        BigDecimal preordain_tail_fee = BigDecimal.valueOf(0.0);//尾款的时候才付运费
        Integer preordain_front_count = 0;

        LocalDateTime localDateTime = LocalDateTime.now();
        String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String key = getAuthUserId() + "_" + format;

        Page<FreeAcquire> freeAcquirePage = FreeAcquire.dao.findActivityByTime(1, 20);
        List<FreeAcquire> list = freeAcquirePage.getList();
        Boolean globalFlag = false;
        //开始循环商品
        for (Object obj : data) {
            OrderItem order_item = new OrderItem();
            JSONObject item = (JSONObject) obj;
            order_item.setOrderId(new_order.getId());
            order_item.setProductId(item.getInteger("id"));
            order_item.setNums(item.getInteger("num"));
            Products pro = Products.dao.getProductBaseById(item.getInteger("id"));

            Jedis jedis = Redis.use().getJedis();
            String freeAcquireProduct = jedis.get(key);
            if (StringUtils.isNotBlank(freeAcquireProduct) && freeAcquireProduct.equals(order_item.getProductId() + "")) {
                jedis.close();
                fail("已经购买过一次该产品,活动期间每天只能购买一件");
                return;
            }
            jedis.close();

            for (int i = 0; i < list.size(); i++) {
                FreeAcquire freeAcquire = list.get(i);
                String freeAcquireProductId = freeAcquire.getProductId();
                if (StringUtils.isNotBlank(freeAcquireProductId) && freeAcquireProductId.equals(order_item.getProductId() + "")) {
                    globalFlag = true;
                }
            }
            Boolean flag = false;
            if (globalFlag && order_item.getNums() > 1) {
                flag = true;
            }


//            if(order_item.getProductId()){
//
//			}
//			globalFlag = list.stream().anyMatch(freeAcquire ->
//					null != freeAcquire.getProductId() && freeAcquire.getProductId().
//							equals(order_item.getProductId() + ""));

//			Boolean finalGlobalFlag = globalFlag;
//			boolean flag = list.stream().anyMatch(freeAcquire ->
//					finalGlobalFlag&& order_item.getNums()> 1);
            if (flag) {
                fail("活动期间" + pro.getProductName() + "每天最多购买一个");
                return;
            }

            if (pro.getBuyQuota() > 0 && item.getInteger("num") > pro.getBuyQuota()) {
                fail("抱歉，" + pro.getProductName() + "商品最多只能购买" + pro.getBuyQuota() + "件");
                return;
            }
            if (pro.getOnlineState() != 1) {
                fail("抱歉，此商品已下架");
                return;
            }
            if (pro.getDelState()) {
                fail("抱歉，此商品不存在");
                return;
            }
            if (pro.getAttrType() == 2)


                if (!StringUtils.isEmpty(invoices)) {
                    JSONObject object = JSONObject.parseObject(invoices);
                    if (object.getInteger("is_invoice").intValue() == 1) {
                        ApiResponse response = OrderInvoiceService.dao.saveInvoice(new_order.getId(), object.getInteger("type"), object.getString("header"), object.getString("ein"), object.getString("email"), object.getString("userName"), object.getString("companyName"), object.getString("bankName"), object.getString("bankNumber"));
                        if (!response.isState()) {
                            renderJson(response);
                            return;
                        }
                        new_order.setIsInvoice(object.getInteger("is_invoice"));
                    }
                } else {
                    fail("抱歉，缺少发票参数");
                    return;
                }
//
            //注意：在这一块 就需要把订单的运费给算出来！
            // 根据运费模板计算运费
            //2019-12-21 新增免运费规则
            BigDecimal post_fee = new BigDecimal(0);


            if (pro.getBuyCountPostFee().intValue() == 0) {
                int template_id = pro.getTemplateId() == null ? 0 : pro.getTemplateId();
                if (template_id != 0 && address != null && TemplateArea.dao.getAreaState(template_id, address.getCountyId() + "")) {
                    post_fee = TemplateArea.dao.trans_fee(item.getInteger("num"), template_id, address.getCountyId() + "");
                } else if (pro.getPostFee().doubleValue() > 0 && null != pracel && true == pracel) { // 判断运费大于0的时候
                    if (AppGlobal.dev_Mode) {
                        post_fee = post_fee.add(new BigDecimal("0.01"));
                    } else {
                        post_fee = pro.getPostFee();
                    }
                }
            } else {
                if (order_item.getNums() < pro.getBuyCountPostFee()) {
                    int template_id = pro.getTemplateId() == null ? 0 : pro.getTemplateId();
                    if (template_id != 0 && address != null && TemplateArea.dao.getAreaState(template_id, address.getCountyId() + "")) {
                        post_fee = TemplateArea.dao.trans_fee(item.getInteger("num"), template_id, address.getCountyId() + "");
                    } else if (pro.getPostFee().doubleValue() > 0 && null != pracel && true == pracel) { // 判断运费大于0的时候
                        if (AppGlobal.dev_Mode) {
                            post_fee = post_fee.add(new BigDecimal("0.01"));
                        } else {
                            post_fee = pro.getPostFee();
                        }
                    }
                }
            }
//
            preordain_tail_fee = preordain_tail_fee.add(post_fee);
            new_order.setExpressAmount(post_fee);
            total_money = total_money.add(post_fee);
            new_order.setShopId(pro.getShopId());
//
            if (globalFlag && null != pracel && false == pracel) {
                List<AgentProductSku> agentProductSkuList = AgentProductSku.dao.findByAgentId(agentId + "");
                for (int i = 0; i < agentProductSkuList.size(); i++) {
                    AgentProductSku agentProductSku = agentProductSkuList.get(i);
                    String agentProductSkuProductId = agentProductSku.getProductId();
                    if (StringUtils.isNotBlank(agentProductSkuProductId) && agentProductSkuProductId.equals(order_item.getProductId() + "")) {
                        Integer num = item.getInteger("num") == null ? 0 : item.getInteger("num");
                        Integer stockNum = agentProductSku.getStockNum() == null ? 0 : agentProductSku.getStockNum();
                        Integer saleNum = agentProductSku.getSaleNum() == null ? 0 : agentProductSku.getSaleNum();
                        if (stockNum <= 0) {
                            fail("抱歉,本地区域代理上库存不足,请选择线上支付或者其他代理区域");
                            return;
                        }
                        agentProductSku.setStockNum(stockNum - num);
                        agentProductSku.setSaleNum(saleNum + num);
                        agentProductSku.update();
                    }
                }

            }
//
//
            String sku_id = item.getString("skuid");
            if (StringUtil.isNotBlank(sku_id) && !globalFlag) {
                ProductSku sku = ProductSku.dao.findById(sku_id);
                if (sku != null) {
                    order_item.setSkuId(sku.getSkuId());
                    order_item.setSkuText(sku.getSkuText());
                    order_item.setSkuCode(sku.getSkuCode());
                    order_item.setUnitPrice(sku.getPrice());

                    if (sku.getStockCount() - 1 <= 0) {
                        fail("抱歉，此商品SKU库存不足");
                        return;
                    }

                    if (pro.getAttrType() == 2) {
                        preordain_front_money = preordain_front_money.add(sku.getGroupPrice());
                        preordain_tail_money = preordain_tail_money.add(sku.getPrice().subtract(sku.getGroupPrice()));
                    }

                    //减少库存
                    sku.setStockCount(sku.getStockCount() - item.getInteger("num"));
                    //增加销售量
                    sku.setSaleCount(sku.getSaleCount() + item.getInteger("num"));
                    sku.update();
                } else {
                    order_item.setUnitPrice(pro.getPrice());
                    if (pro.getAttrType() == 2) {
                        preordain_front_money = preordain_front_money.add(pro.getPreordainFrontMoney());
                        preordain_tail_money = preordain_tail_money.add(pro.getPreordainTailMoney());
                    }
                }
            } else {
                order_item.setUnitPrice(pro.getPrice());
                if (pro.getAttrType() == 2) {
                    preordain_front_money = preordain_front_money.add(pro.getPreordainFrontMoney());
                    preordain_tail_money = preordain_tail_money.add(pro.getPreordainTailMoney());
                }
            }
            new_order.setType(pro.getAttrType()); // 1单买  2 预售
            order_item.setPrice(order_item.getUnitPrice().multiply(BigDecimal.valueOf(order_item.getNums())));
            if (pro.getAttrType() == 2) {
                preordain_front_count += order_item.getNums();
                total_money = total_money.add(preordain_front_money).add(preordain_tail_money);
            } else {
                total_money = total_money.add(order_item.getPrice());
            }
            pro.setSaleCount(pro.getSaleCount() + order_item.getNums());
            pro.update();
            order_item.save();

            //清除购物车
            Db.update("delete from t_order_cart where user_id = ? and product_id = ?", getAuthUserId(), pro.getId());
        }


        if (null != pracel && false == pracel && globalFlag) {
            new_order.setAgentId(agentId);
        } else if (new_order.getRegisterOrder() == null || new_order.getRegisterOrder() == 0) {
            //调用任大佬的代理商代码
            Map<Integer, Object> map = AgentService.dao.detectionUserInAgent(getAuthUser(), new_order.getAddressId());

            if (map != null) {
                Agent agent = (Agent) map.get(0);
                if (agent != null) {
                    if (Agent.TYPE_AREA.equals(agent.getType())) {
                        AgentCity agentCity = (AgentCity) map.get(1);
                        if (agentCity != null)
                            new_order.setAgentCityId(agentCity.getId());
                    }
                }
            }
        }
        //在这里判断是否使用了优惠卷
        if (null != pracel && new_order.getType() != null && new_order.getType() == 1 && !StringUtils.isEmpty(coupon_id)) {
            UserCoupon userCoupon = UserCoupon.dao.findByUserIdAndCoupon(getAuthUserId(), coupon_id);
            if (userCoupon != null && userCoupon.getUseState() == 0) {
                if (userCoupon.getRuleMoney().compareTo(BigDecimal.ZERO) > 0 && total_money.compareTo(userCoupon.getRuleMoney()) >= 0) {
                    new_order.setCouponAmount(userCoupon.getFaceAmount());
                    total_money = total_money.subtract(userCoupon.getFaceAmount());
                    new_order.setCouponId(coupon_id);

                    userCoupon.setUseState(99);
                    userCoupon.setUseDate(new Date());
                    userCoupon.update();
                }
            }
        }
        //这里判断是否使用了账户余额
        if (isUserHongbao != null && isUserHongbao == 1) {
            //使用用户yue
            WeixinUser authUser = getAuthUser();
            BigDecimal accountBalance = authUser.getAccountBalance();
            if (accountBalance != null && accountBalance.compareTo(new BigDecimal(0.0)) == 1) {
                if (accountBalance.compareTo(total_money) != -1) {
                    accountBalance = total_money;
                }
                new_order.setIsUserHongbao(isUserHongbao);
                total_money = total_money.subtract(accountBalance);
                new_order.setUserHongbaoPrice(accountBalance);

                authUser.setIceAccount(authUser.getIceAccount().add(accountBalance));
                authUser.setAccountBalance(authUser.getAccountBalance().subtract(accountBalance));
                authUser.update();

                UserRebate userRebate = new UserRebate();
                userRebate.setId(IdGenerateUtils.getId());
                userRebate.setOrderId(new_order.getId());
                userRebate.setState(0);
                userRebate.setStatus(0);
                userRebate.setRemark("订单使用余额");
                userRebate.setCreateTime(new Date());
                userRebate.setPrice(accountBalance);
                userRebate.setUserId(authUser.getId());
                userRebate.save();
            }
        }

        new_order.setItemAmount(total_money);
        new_order.setTotalAmount(total_money);// 总价格


        if (new_order.getTotalAmount().compareTo(new BigDecimal(0.00)) == 0) {
            new_order.setState(Order.State_Wait_Send_Express);//等待支付
            new_order.setPayType(pay_type);//支付方式
            new_order.save();


            Order order_new = new Order();
            order_new.setId(new_order.getId());
            order_new.setPayTime(new Date());
            order_new.setPayState(2);
            order_new.setPayType(6);
            if (order_new.update()) {
                /*用户成功下单后推送给代理商*/
                Integer userId = order_new.getUserId();
                WeixinUser payUser = WeixinUser.dao.findById(userId);
                if (!(null != pracel && false == pracel && null != agentId)) {
                    agentId = order_new.getAgentId();
                }
                Agent agent = Agent.dao.findById(agentId);
                if (agent != null) {
                    WeixinUser agentUser = WeixinUser.dao.findById(agent.getUserId());
                    String payTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new_order.getPayTime());

                    BigDecimal totalAmount = order_new.getTotalAmount();
                    if (AppGlobal.dev_Mode) {
                        total_money = new BigDecimal(0.01);
                    }

                    AgentService.dao.sendSaveTemplateMsg(order_new.getId(), payUser.getNickname(), totalAmount.toString()
                            , payTimeStr, payUser.getBindPhone(), agentUser.getOpenid());
                    //处理成功
                }
            } else {
            }
            renderJson(new ApiResponse(true, "余额支付成功!", order_new.getId()));
            return;
        } else {
            new_order.setState(Order.State_Wait_Pay);//等待支付
            new_order.setPayType(pay_type);//支付方式
            new_order.save();
        }

        JSONObject pay_json;
        if (isXapp()) {
            if (new_order.getType() == 2) { //预售商品
                if (new_order.getType() == 2) {
                    OrderPresale presale = new OrderPresale();
                    presale.setOrderId(new_order.getId());
                    presale.setOpenid(getAuthUser().getId() + "");
                    presale.setType(1);
                    presale.setDanjia(preordain_front_money);
                    presale.setMoney(preordain_front_money.multiply(new BigDecimal(preordain_front_count + "")));
                    presale.setBuyCount(preordain_front_count);
                    presale.setPayType(1);
                    presale.save();

                    OrderPresale new_presale = new OrderPresale();
                    new_presale.setOrderId(new_order.getId());
                    new_presale.setOpenid(getAuthUser().getId() + "");
                    new_presale.setType(2);
                    new_presale.setDanjia(preordain_tail_money);
                    new_presale.setMoney((preordain_tail_money.multiply(new BigDecimal(preordain_front_count + ""))).add(preordain_tail_fee));
                    new_presale.setBuyCount(preordain_front_count);
                    new_presale.setPayType(1);
                    new_presale.save();
                }


                double payPrice = (preordain_front_money.multiply(new BigDecimal(preordain_front_count + ""))).doubleValue();
                if (AppGlobal.dev_Mode) {
                    payPrice = 0.01;
                }
                pay_json = JSONObject.parseObject(
                        KusyApi.mini_wxpay(KusyUtil.Api_key, KusyUtil.Sign_Key, getWxappId(),
                                getAuthUser().getOpenid(), new_order.getId(), payPrice,
                                "中科易购购买商品", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/xapp"));

            } else {

                double payPrice = new_order.getTotalAmount().doubleValue();
                if (AppGlobal.dev_Mode) {
                    payPrice = 0.01;
                }

                pay_json = JSONObject.parseObject(KusyApi.mini_wxpay(
                        KusyUtil.Api_key, KusyUtil.Sign_Key, getWxappId(),
                        getAuthUser().getOpenid(), new_order.getId(),
                        payPrice, "中科易购购买商品",
                        AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/xapp"));
            }
            System.err.println(new_order.getId());
            if (pay_json.getInteger("status") == 10000) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                pay_json.put("trade_no", new_order.getId());
                pay_json.put("createtime", sdf.format(new Date()));
                System.err.println("orderid：" + pay_json.getString("orderid"));
                //2019-11-14 保存新的id
                new_order.setKusyOrderId(pay_json.getString("orderid"));
                if (new_order.getType() == 2) {
                    OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(new_order.getId(), 1);
                    presale.setPayOrderid(pay_json.getString("orderid"));
                    presale.update();
                }
                new_order.update();
                success(pay_json);
            } else {
                log.error("KusyApi 小程序支付参数错误！，返回参数：" + JsonKit.toJson(pay_json));
                fail(pay_json.getString("message"));
            }
        } else {
            if (pay_type.intValue() == 3) {
                Map<String, Object> signData = new HashMap<String, Object>();
                signData.put("order_id", new_order.getId());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/alipay/callback");
                if (new_order.getType() == 2) { //预售商品
                    if (new_order.getType() == 2) {
                        OrderPresale presale = new OrderPresale();
                        presale.setOrderId(new_order.getId());
                        presale.setOpenid(getAuthUser().getId() + "");
                        presale.setType(1);
                        presale.setDanjia(preordain_front_money);
                        presale.setMoney(preordain_front_money.multiply(new BigDecimal(preordain_front_count + "")));
                        presale.setBuyCount(preordain_front_count);
                        presale.setPayType(1);
                        presale.save();

                        OrderPresale new_presale = new OrderPresale();
                        new_presale.setOrderId(new_order.getId());
                        new_presale.setOpenid(getAuthUser().getId() + "");
                        new_presale.setType(2);
                        new_presale.setDanjia(preordain_tail_money);
                        new_presale.setMoney((preordain_tail_money.multiply(new BigDecimal(preordain_front_count + ""))).add(preordain_tail_fee));
                        new_presale.setBuyCount(preordain_front_count);
                        new_presale.setPayType(1);
                        new_presale.save();
                    }
                    signData.put("total_fee", preordain_front_money.multiply(new BigDecimal(preordain_front_count + "")));
                } else {
                    signData.put("total_fee", new_order.getTotalAmount());
                }
                pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
                success(pay_json);
            } else {
                Map<String, String> stringStringMap = sign_pay(new_order.getId(),total_money);

//				Map<String,Object> signData=new HashMap<String, Object>();
//				signData.put("trade_no",new_order.getId());
//				signData.put("description","中科易购购买商品");
//				signData.put("detail",new_order.getOrderProductName());
//				signData.put("nonce_str","中科易购购买商品");
//				signData.put("sign","中科易购购买商品");
//
//				if(new_order.getType()==2){ //预售商品
//					if(new_order.getType()==2){
//						OrderPresale presale =new OrderPresale();
//						presale.setOrderId(new_order.getId());
//						presale.setOpenid(getAuthUser().getId()+"");
//						presale.setType(1);
//						presale.setDanjia(preordain_front_money);
//						presale.setMoney(preordain_front_money.multiply(new BigDecimal(preordain_front_count+"")));
//						presale.setBuyCount(preordain_front_count);
//						presale.setPayType(1);
//						presale.save();
//
//						OrderPresale new_presale =new OrderPresale();
//						new_presale.setOrderId(new_order.getId());
//						new_presale.setOpenid(getAuthUser().getId()+"");
//						new_presale.setType(2);
//						new_presale.setDanjia(preordain_tail_money);
//						new_presale.setMoney((preordain_tail_money.multiply(new BigDecimal(preordain_front_count+""))).add(preordain_tail_fee));
//						new_presale.setBuyCount(preordain_front_count);
//						new_presale.setPayType(1);
//						new_presale.save();
//					}
//					signData.put("total_fee",preordain_front_money.multiply(new BigDecimal(preordain_front_count+"")));
//				}else{
//
//					signData.put("total_fee",new_order.getTotalAmount());
//				}
//				signData.put("notify_url",AppGlobal.Host_Domain_Name+"/xapp/order/pay/notify");
//				signData.put("createtime",new Date());
//				pay_json=JSONObject.parseObject(JsonKit.toJson(signData));
                pay_json = JSONObject.parseObject(JsonKit.toJson(stringStringMap));
                success(pay_json);
            }

        }

    }

    //普通商品订单支付取消后再次支付 调用此接口
    public void againPay() {
        String order_id = getPara("order_id");
        Order order = Order.dao.findById(order_id);
        if (order == null) {
            fail("抱歉，此订单不存在");
            return;
        }
        if (order.getType() != 1 && order.getType() != 6) {
            fail("抱歉，此订单不属于普通商品订单");
            return;
        }
        if (order.getState() != Order.State_Wait_Pay) {
            fail("抱歉，此订单状态不是待支付");
            log.error("普通商品订单支付取消后再次支付 ，order_id：" + order_id + " ， 状态是：" + order.getState());
            return;
        }
        OrderItem orderItem = OrderItem.dao.getOrderItemByOrderId(order_id);
        Products products = Products.dao.findById(orderItem.getProductId());
        if (products == null || products.getOnlineState() != 1) {
            fail("抱歉，此商品不存在或已下架");
            return;
        }
        JSONObject pay_json;
        if (isXapp()) {
            BigDecimal totalAmount = order.getTotalAmount();
            if (AppGlobal.dev_Mode) {
                totalAmount = new BigDecimal(0.01);
            }
            pay_json = JSONObject.parseObject(KusyApi.mini_wxpay(KusyUtil.Api_key, KusyUtil.Sign_Key, getWxappId(), getAuthUser().getOpenid(), order.getId(), totalAmount.doubleValue(), "中科易购购买商品", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/xapp"));
            if (pay_json.getInteger("status") == 10000) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                pay_json.put("trade_no", order.getId());
                pay_json.put("createtime", sdf.format(new Date()));
                //2019-11-14 保存新的id
                order.setKusyOrderId(pay_json.getString("orderid"));
                order.update();
                success(pay_json);
            } else {
                log.error("KusyApi 小程序支付参数错误！，返回参数：" + JsonKit.toJson(pay_json));
                fail(pay_json.getString("message"));
            }
        } else {
            if (order.getPayType().intValue() == 3) {
                Map<String, Object> signData = new HashMap<String, Object>();
                signData.put("order_id", order.getId());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/alipay/callback");
                signData.put("total_fee", order.getTotalAmount());
                pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
                success(pay_json);
            } else {
                Map<String, Object> signData = new HashMap<String, Object>();
                signData.put("trade_no", order.getId());
                signData.put("description", "中科易购购买商品");
                signData.put("detail", "中科易购购买商品");
                signData.put("total_fee", order.getTotalAmount());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify");
                signData.put("createtime", new Date());
                pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
                Map<String, String> stringStringMap = sign_pay(order_id,order.getTotalAmount());
                pay_json = JSONObject.parseObject(JsonKit.toJson(stringStringMap));
                success(pay_json);
            }


        }
    }

    //预售商品取消订单 再次支付 定金 调用此接口
    public void advanceAgainPay() {
        String order_id = getPara("order_id");
        Order order = Order.dao.findById(order_id);
        if (order == null) {
            fail("抱歉，此订单不存在");
            return;
        }
        if (order.getType() != 2) {
            fail("抱歉，此订单不属于预售商品订单");
            return;
        }
        if (order.getState() != Order.State_Wait_Pay) {
            fail("抱歉，此订单状态不是待支付");
            log.error("预售商品订单支付取消后再次支付 ，order_id：" + order_id + " ， 状态是：" + order.getState());
            return;
        }
        OrderItem orderItem = OrderItem.dao.getOrderItemByOrderId(order_id);
        Products products = Products.dao.findById(orderItem.getProductId());
        if (products == null || products.getOnlineState() != 1) {
            fail("抱歉，此商品不存在或已下架");
            return;
        }
        OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order_id, 1);
        if (presale == null) {
            fail("抱歉，此订单未生成");
            return;
        }
        if (presale.getState() != 1) {
            fail("抱歉，此订单已支付");
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject pay_json;
        if (isXapp()) {
            pay_json = JSONObject.parseObject(KusyApi.mini_wxpay(KusyUtil.Api_key, KusyUtil.Sign_Key, getWxappId(), getAuthUser().getOpenid(), order.getId(), presale.getMoney().doubleValue(), "中科易购购买商品", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/xapp"));
            if (pay_json.getInteger("status") == 10000) {
                pay_json.put("trade_no", order.getId());
                pay_json.put("createtime", sdf.format(new Date()));
                //2019-11-14 保存新的id
                order.setKusyOrderId(pay_json.getString("orderid"));
                if (order.getType() == 2) {
                    OrderPresale dj = OrderPresale.dao.findByOrderIdAndType(order.getId(), 1);
                    dj.setPayOrderid(pay_json.getString("orderid"));
                    dj.update();
                }
                success(pay_json);
            } else {
                log.error("KusyApi 小程序支付参数错误！，返回参数：" + JsonKit.toJson(pay_json));
                fail(pay_json.getString("message"));
            }
        } else {
            Map<String, Object> signData = new HashMap<String, Object>();
            if (order.getPayType().intValue() == 3) {
                signData.put("order_id", order.getId());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/alipay/callback");
                signData.put("total_fee", presale.getMoney());
            } else {
                signData.put("trade_no", order.getId());
                signData.put("description", "中科易购购买商品");
                signData.put("detail", "中科易购购买商品");
                signData.put("total_fee", presale.getMoney());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify");
                signData.put("createtime", sdf.format(order.getCreatetime()));
            }
            pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
            success(pay_json);
        }


    }

    //再付款前 验证此商品 尾款支付时间是否过期
    public static final boolean is_buy(Date endTime) {
        Date nowDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(nowDate);
        Calendar begin = Calendar.getInstance();
        begin.setTime(endTime);
        if (begin.after(date)) {
            return true;
        } else {
            return true;
        }
    }

    //去付尾款
    public void payTail() {
        String order_id = getPara("order_id");
        Order order = Order.dao.findById(order_id);
        if (order == null) {
            fail("抱歉，此订单不存在");
            return;
        }
        if (order.getType() != 2) {
            fail("抱歉，此订单不属于预售订单");
            return;
        }
        OrderItem orderItem = OrderItem.dao.getOrderItemByOrderId(order_id);
        Products products = Products.dao.findById(orderItem.getProductId());
        if (products == null || products.getOnlineState() != 1) {
            fail("抱歉，此商品不存在或已下架");
            return;
        }
        //判断当前是否 尾款时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = new Date();
        Date beginDate = null;
        Date endDate = null;
        try {
            String begin_str = sdf_date.format(products.getTailPayTime()) + " 00:00:00";
            String end_str = sdf_date.format(products.getTailPayTime()) + " 23:59:59";
            beginDate = sdf.parse(begin_str);
            endDate = sdf.parse(end_str);
            Calendar date = Calendar.getInstance();
            date.setTime(nowDate);
            Calendar begin = Calendar.getInstance();
            begin.setTime(beginDate);
            Calendar end = Calendar.getInstance();
            end.setTime(endDate);
            if (date.after(begin) == false || date.before(end) == false) {
                fail("您当前不在尾款支付时间内");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取尾款支付时间异常, 订单号：" + order_id + " ，error：" + e);
            fail("获取尾款支付时间异常");
            return;
        }

        OrderPresale presale = OrderPresale.dao.findByOrderIdAndType(order_id, 2);
        if (presale == null) {
            fail("抱歉，此订单未生成");
            return;
        }
        JSONObject pay_json;
        if (isXapp()) {
            pay_json = JSONObject.parseObject(KusyApi.mini_wxpay(KusyUtil.Api_key, KusyUtil.Sign_Key, getWxappId(), getAuthUser().getOpenid(), order.getId() + "_" + presale.getId(), presale.getMoney().doubleValue(), "中科易购购买商品", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/tail_xapp"));
            if (pay_json.getInteger("status") == 10000) {
                pay_json.put("trade_no", order.getId());
                pay_json.put("createtime", sdf.format(new Date()));
                //2019-11-14 保存新的id
                order.setKusyOrderId(pay_json.getString("orderid"));
                if (order.getType() == 2) {
                    OrderPresale dj = OrderPresale.dao.findByOrderIdAndType(order.getId(), 2);
                    dj.setPayOrderid(pay_json.getString("orderid"));
                    dj.update();
                }
                success(pay_json);
            } else {
                log.error("KusyApi 小程序支付参数错误！，返回参数：" + JsonKit.toJson(pay_json));
                fail(pay_json.getString("message"));
            }
        } else {
            Map<String, Object> signData = new HashMap<String, Object>();
            if (order.getPayType().intValue() == 3) {
                signData.put("order_id", order.getId());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/alipay/callback/tail_app");
                signData.put("total_fee", presale.getMoney());
            } else {
                signData.put("trade_no", order.getId() + "_" + presale.getId());
                signData.put("description", "中科易购购买商品");
                signData.put("detail", "中科易购购买商品");
                signData.put("total_fee", presale.getMoney());
                signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/order/pay/notify/tail_app");
                signData.put("createtime", sdf.format(order.getCreatetime()));
            }
            pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
            success(pay_json);
        }
    }
}